package com.lesserpand.lspand.story.item.service.impl;

import com.lesserpand.lspand.story.item.entity.NewInfoQuery;
import com.lesserpand.lspand.story.item.service.NewInfoService;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Delete;
import io.searchbox.core.Get;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import io.searchbox.core.Update;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.Objects;

/**
 * @author bailuo
 * @version 2.0
 * @Description TODO
 * @Date Created in 2018/11/24 14:15
 */
public class NewInfoServiceImpl implements NewInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(NewInfoServiceImpl.class);

    @Resource
    JestClient jestClient;

    /**
     * 新增数据到es，设置数据库id为es id。
     *
     * @param indexName
     * @param typeName
     * @param o
     * @param <T>
     * @return
     */
    @Override
    public <T> JestResult save(String indexName, String typeName, T o) {
        Class clazz = o.getClass();
        String id;
        JestResult jestResult = null;
        try {
            Field field = clazz.getDeclaredField("id");
            field.setAccessible(true);
            id = String.valueOf(field.get(o));
            Index index = new Index.Builder(o).id(id).index(indexName).type(typeName).build();
            jestResult = jestClient.execute(index);
        } catch (Exception e) {
            LOGGER.error("", e);
        }
        return jestResult;
    }

    public <T> JestResult pagination(T o, NewInfoQuery query, String indexName, String typeName) {
        int pageNum = null == query.getPageNum() ? 1 : query.getPageNum();
        int pageSize = null == query.getPageSize() ? 10 : query.getPageSize();

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.from((pageNum - 1) * pageSize);
        searchSourceBuilder.size(pageSize);

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        String title = query.getTitle();
        if (null != title) {
            boolQueryBuilder.must(QueryBuilders.termQuery("title", title));
        }

        String keyWord = query.getKeyWord();
        if (null != keyWord) {
            boolQueryBuilder.must(QueryBuilders.termQuery("details", keyWord));
        }

        Timestamp startTime = query.getStartTime();
        Timestamp endTime = query.getEndTime();
        if (null != startTime && null != endTime) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("gmtCreate").from(startTime).to(endTime));
        }

        searchSourceBuilder.query(boolQueryBuilder);
        Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(indexName).addType(typeName).build();
        SearchResult result = null;
        Long total = 0L;
        try {
            result = jestClient.execute(search);
            total = result.getTotal();
            if (!Objects.equals(total, 0L)) {
                // List<SearchResult.Hit<T, Void>> hits = result.getHits();
            }
        } catch (Exception e) {

        }
        return result;
    }

    /**
     * 根据id查询es数据
     *
     * @param index
     * @param type
     * @param o
     * @param id
     * @param <T>
     * @return
     */
    @Override
    public <T> T getById(String index, String type, T o, String id) {
        Get get = new Get.Builder(index, id).type(type).build();
        T object = null;
        try {
            JestResult result = jestClient.execute(get);
            object = (T) result.getSourceAsObject(o.getClass());
        } catch (Exception e) {
            LOGGER.error("", e);
        }
        return object;
    }


    /**
     * 根据id删除es数据
     *
     * @param index
     * @param type
     * @param id
     * @return
     */
    @Override
    public JestResult deleteById(String index, String type, String id) {
        Delete delete = new Delete.Builder(id).index(index).type(type).build();
        JestResult result = null;
        try {
            result = jestClient.execute(delete);
        } catch (Exception e) {
            LOGGER.error("", e);
        }

        return result;
    }

    /**
     * 根据id更新es数据
     *
     * @param index
     * @param type
     * @param data
     * @param id
     * @return
     */
    @Override
    public JestResult update(String index, String type, String data, String id) {
        Update update = new Update.Builder(data).index(index).type(type).id(id).build();
        JestResult result = null;

        try {
            result = jestClient.execute(update);
        } catch (Exception e) {
            LOGGER.error("", e);
        }
        return result;
    }

}
